package cn.spike.rockcc.service.impl;

import cn.spike.rockcc.agg.AggPageList;
import cn.spike.rockcc.dto.BucketVo;
import cn.spike.rockcc.dto.CourseEsDto;
import cn.spike.rockcc.dto.SearchDto;
import cn.spike.rockcc.mapper.HighlightResultMapper;
import cn.spike.rockcc.repository.CourseSearchRepository;
import cn.spike.rockcc.result.PageList;
import cn.spike.rockcc.service.ISearchService;
import cn.spike.rockcc.util.AssertUtil;
import com.mysql.cj.QueryBindings;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.queryparser.xml.QueryBuilderFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:spike
 * @create:2023-03-16 16:57
 */
@Service
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private CourseSearchRepository courseSearchRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private HighlightResultMapper highlightResultMapper;

    @Override
    public void save(CourseEsDto courseEsDto) {
        courseSearchRepository.save(courseEsDto);
    }

    @Override
    public PageList<CourseEsDto> searchCourse(SearchDto searchDto) {
        //创建查询对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //----------------------构造查询条件，分页查询--------------------------------
        nativeSearchQueryBuilder.withPageable(PageRequest.of((searchDto.getPage()-1)*searchDto.getRows()
                ,searchDto.getRows()));
        //----------------------构造查询条件，排序字段和排序方式--------------------------------
        SortOrder orderType = SortOrder.ASC.toString().equals(searchDto.getSortType())?SortOrder.ASC:SortOrder.DESC;
        nativeSearchQueryBuilder.withSort(
                SortBuilders.fieldSort(checksortField(searchDto.getSortField())).order(orderType));
        //-------------------------------创建组合查询对象------------------------------------------
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //-------------------------------组合查询条件------------------------------------------
        if(!StringUtils.isEmpty(searchDto.getKeyword()))
            boolQueryBuilder.must(QueryBuilders.matchQuery("name",searchDto.getKeyword()));
        if(!StringUtils.isEmpty(searchDto.getChargeName()))
            boolQueryBuilder.filter(QueryBuilders.termQuery("charge",searchDto.getChargeName()));
        if(!StringUtils.isEmpty(searchDto.getGradeName()))
            boolQueryBuilder.filter(QueryBuilders.termQuery("gradeName",searchDto.getGradeName()));
        if(searchDto.getCourseTypeId()!=null)
            boolQueryBuilder.filter(QueryBuilders.termQuery("courseTypeId",searchDto.getCourseTypeId()));
        if(searchDto.getPriceMin()!=null)
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(searchDto.getPriceMin()));
        if(searchDto.getPriceMax()!=null)
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(searchDto.getPriceMax()));
        //---------------------------------------高亮处理-------------------------------------------------
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("name")
                .preTags("<font color='red'>")
                .postTags("</font>");
        //----------------------------------------聚合查询------------------------------------------------
        //gradeNameAgg - 取出的别名 / gradeName - 对哪一个字段做聚合
        TermsAggregationBuilder gradeNameAggBuilder = AggregationBuilders.terms("gradeNameAgg").field("gradeName");
        TermsAggregationBuilder chargeAggBuilder = AggregationBuilders.terms("chargeNameAgg").field("charge");
        //---------------------------------------组装查询条件-------------------------------------------
        nativeSearchQueryBuilder.addAggregation(gradeNameAggBuilder).addAggregation(chargeAggBuilder);
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        nativeSearchQueryBuilder.withHighlightBuilder(highlightBuilder);
        //-------------------------------------------查询-----------------------------------------------------
        AggregatedPage<CourseEsDto> page = elasticsearchRestTemplate.queryForPage(nativeSearchQueryBuilder.build(),
                CourseEsDto.class,
                highlightResultMapper);

        Map<String, List<BucketVo>> aggMap = new HashMap();
        Map<String, Aggregation> AggregationMap = page.getAggregations().asMap();
        AggregationMap.keySet().forEach(keyAgg->{
            List<BucketVo> buckets = new ArrayList<>();
            ParsedStringTerms aggregation = (ParsedStringTerms) AggregationMap.get(keyAgg);
            aggregation.getBuckets().forEach(bucket -> {
                buckets.add(new BucketVo(bucket.getKey().toString(),bucket.getDocCount()));
            });
            aggMap.put(aggregation.getName(),buckets);
        });
        return new AggPageList<CourseEsDto>(page.getTotalElements(),page.getContent(),aggMap);
    }


    private String checksortField(String sortField){
        if(sortField==null)return "saleCount";
        switch (sortField){
            case "jg": return "price";
            case "xp": return "onlineTime";
            case "pl": return "commentCount";
            case "rq": return "viewCount";
            default:return "saleCount";
        }

    }

}
